package com.huarun.module.timer;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.huarun.common.util.DateUtils;
import com.huarun.common.util.HttpRequest;
import com.huarun.common.util.PropertyUtil;
import com.huarun.common.util.SpringContextUtils;
import com.huarun.faseplus.Data;
import com.huarun.faseplus.SubjectBean;
import com.huarun.module.sys.bean.Subject;
import com.huarun.module.sys.dao.SubjectDao;
import com.huarun.module.sys.service.ISubjectServiceNew;
import com.huarun.module.sys.service.impl.SubjectServiceImplNew;
import com.huarun.module.timer.bean.SynInfo;
import com.huarun.module.timer.impl.SynInfoServiceImpl;

/**
 * @author dzm
 * @创建时间 2018-11-02 18:01
 * @Description 天数据统计
 * 
 */
public class ScheduledDDayJob implements Job {
	private static Logger log = LoggerFactory.getLogger(ScheduledDDayJob.class);
	//
	private ISubjectServiceNew subjectService = (ISubjectServiceNew) SpringContextUtils
			.getBeanByClass(SubjectServiceImplNew.class);
	private ISynInfoService synInfoService = (ISynInfoService) SpringContextUtils
			.getBeanByClass(SynInfoServiceImpl.class);
	private SubjectDao subjectDao = (SubjectDao) SpringContextUtils
			.getBeanByClass(SubjectDao.class);

	// 执行具体内容
	@Override
	public void execute(JobExecutionContext context) {

		log.info("--------------day job start-----------------");
		int total = 0;
		try {
//			Map<String, Object> delParams = new HashMap<String, Object>();
//			delParams.put("projectId", PropertyUtil.getProperty("huarun_d_project_id"));
//			subjectService.deleteAll(delParams);

			//			String uri=(String) context.get("faceUrl");
			String proId = PropertyUtil.getProperty("huarun_d_project_id");
			HttpRequest hq = new HttpRequest();
			String uri = PropertyUtil.getProperty("face_url_D");
			String url = uri + PropertyUtil.getProperty("appLogin");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("username", PropertyUtil.getProperty("face_username_d"));
			map.put("password", PropertyUtil.getProperty("face_password_d"));
			String[] result = hq.sendPost(url, map);
			System.out.println(result[0]);
			System.out.println("##########");
			System.out.println(result[1]);
			String cookie = result[1];
			String subjectListurl = uri + PropertyUtil.getProperty("getSubjectList") + "?";
			Map<String, Object> params = new HashMap<>();
			// 'employee' - 员工; 'visitor' - 所有访客; 'vip' - VIP访客
			params.put("category", "employee");
			params.put("name", "");
			params.put("order", "");
			params.put("page", 1);
			params.put("size", 10);
			String resultStr = hq.sendGet(subjectListurl, params, cookie);
			System.out.println("获取到的Json传信息  " + resultStr);
			if (null != resultStr) {
				// SubjectBean subject = JSON.parseObject(resultStr, SubjectBean.class);//
				// jsonString转为java对象
				SubjectBean subject = JSON.parseObject(resultStr, new TypeReference<SubjectBean>() {});
				if (null != subject) {
					SynInfo info = new SynInfo();
					info.setTableName("subject");
					info.setTotal(subject.getPage().getCount());
					info.setProjectId(proId);
					info.setSynDate(new Date());
					info.setStatus(1);
					// 查询同步表中用户数据是否没同步，如果是，往user表中插入数据
					int taotal = subject.getPage().getTotal();
					int resultCount = 0;
					int resultCountUnchange = 0;
					Subject subjectDb = null;
					Map<String, Object> params1 = new HashMap<>();
					// 'employee' - 员工; 'visitor' - 所有访客; 'vip' - VIP访客
					params1.put("projectId", proId);
					List<Integer> idList = subjectDao.findSubjectIdList(params1);
					for (int i = 1; i <= taotal; i++) {
						params.put("page", i + "");
						params.put("count", 10 + "");
						String subString = hq.sendGet(subjectListurl, params, cookie);
						if (null != subString && subString.length() > 0) {
							Map<String, Object> subMap = JSONObject.parseObject(subString);
							List<Data> data = JSON.parseObject(subMap.get("data").toString(),
									new TypeReference<List<Data>>() {});
							List<Subject> subjectList = new ArrayList<Subject>();
							for (int j = 0; j < data.size(); j++) {
								Data d = data.get(j);
								subjectDb = new Subject();
								subjectDb.setAvatar(d.getAvatar());
								if (null != d.getBirthday()) {
									subjectDb.setBirthday(DateUtils.StringToDate(d.getBirthday()));
								}
								subjectDb.setComeFrom(d.getComeFrom());
								subjectDb.setCompanyId(d.getCompanyId());
								subjectDb.setDepartment(d.getDepartment());
								subjectDb.setDescription(d.getDescription());
								if (null != d.getEntryDate()) {
									subjectDb.setEntryDate(DateUtils.StringToDate(d.getEntryDate()));
								}
								subjectDb.setFaceId(d.getId());
								subjectDb.setGender((short) d.getGender());
								subjectDb.setInterviewee(d.getInterviewee());
								subjectDb.setJobNumber(d.getJobNumber());
								subjectDb.setPurpose(d.getPurpose());
								subjectDb.setPhone(d.getPhone());
								subjectDb.setRealName(d.getName());
								subjectDb.setRemark(d.getRemark());
								subjectDb.setStartTime(d.getStartTime());
								subjectDb.setSyncTime(new Date());
								subjectDb.setSubjectType((short) d.getSubjectType());
								subjectDb.setTitle(d.getTitle());
								subjectDb.setVisitNotify(d.isVisitNotify());
								subjectDb.setProjectId(proId);
								//判断是否已经存在，对比关键字段，实现增量更新 -by mengsg 2020-3-11  --start
								map.put("faceId", d.getId());
								map.put("projectId", proId);
								Subject subjectHis = subjectDao.getSubjectByParams(map);
								if(subjectHis == null) {
									subjectService.save(subjectDb);
								}else if(!subjectHis.equals(subjectDb)) {
									System.out.println("list长度="+idList.size());
									subjectDb.setId(subjectHis.getId());
									subjectService.update(subjectDb);
									idList.remove(subjectHis.getId());
								}else {
									idList.remove(subjectHis.getId());
									System.out.println("list长度="+idList.size());
									resultCountUnchange++;
									System.out.println("未变化-"+resultCountUnchange);
								}
								//by mengsg 2020-3-11  --end
								resultCount++;
								subjectList.add(subjectDb);
							}
						}

					}
					//删除不存在的数据 -by mengsg 2020-3-11  --start
					for (Integer id : idList) {
						subjectService.delete(id);
					}
					//by mengsg 2020-3-11  --end
					info.setSuccessCount(resultCount);
					synInfoService.save(info);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			total = 0;
			SynInfo info = new SynInfo();
			info.setTableName("subject");
			info.setTotal(total);
			info.setProjectId(PropertyUtil.getProperty("huarun_d_project_id"));
			info.setSynDate(new Date());
			info.setSuccessCount(0);
			info.setStatus(2);
			synInfoService.save(info);
		}
		log.info("----------------------------day job end------------------------------");
	}

}
